package DAO;

import Utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();
    private Connection conn= JDBCUtils.getConn();
    public int update(String sql, Object... params) {
        try {
            return queryRunner.update(conn,sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public <T> T queryForOne(String sql, Class<T> clazz, Object... params) {
        try {
            System.out.println(conn);
            return queryRunner.query(conn,sql,new BeanHandler<T>(clazz),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public <T> List<T> queryForList(String sql, Class<T> clazz, Object... params) {
        try {
            return queryRunner.query(conn, sql, new BeanListHandler<T>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public List<Map<String, Object>> queryForListMap(String sql, Object... params) {
        try {
            return queryRunner.query(conn,sql,new MapListHandler(),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
